package com.yj.contract.service;

import com.yj.common.enums.OAUserRoleLevel;
import com.yj.common.mapper.PaginationMapper;
import com.yj.config.mybatis.pagination.Page;
import com.yj.contract.dto.ContractChangeStatusDto;
import com.yj.contract.dto.ContractListDto;
import com.yj.oa.entity.system.OAContract;
import com.yj.oa.entity.system.OADepartmentConfig;
import com.yj.oa.entity.system.OAUserConfig;
import com.yj.oa.entity.system.OAUserInfo;
import com.yj.oa.mapper.OAContractMapper;
import com.yj.oa.mapper.OADepartmentConfigMapper;
import com.yj.oa.mapper.OAUserConfigMapper;
import com.yj.oa.mapper.UserRelationshipMapper;
import com.yj.oa.service.OAInfoService;
import com.yj.transport.service.TransportInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright 2017 (C) Yunjian-VC
 * Created on : 2017/12/8
 * Author     : Unbelievable9
 **/
@Service
public class ContractService {

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM");

    @Autowired
    PaginationMapper paginationMapper;

    @Autowired
    OAContractMapper oaContractMapper;

    @Autowired
    OAUserConfigMapper oaUserConfigMapper;

    @Autowired
    OADepartmentConfigMapper oaDepartmentConfigMapper;

    @Autowired
    UserRelationshipMapper userRelationshipMapper;;

    @Autowired
    OAInfoService oaInfoService;

    @Autowired
    TransportInfoService transportInfoService;

    /**
     * 根据筛选条件获取目标用户ID列表
     *
     * @param contractListDto 合同列表筛选对象
     * @param oaUserInfo      用户信息
     */
    private List<String> findUserIDForList(ContractListDto contractListDto,
                                           OAUserInfo oaUserInfo) {
        OAUserConfig oaUserConfig = oaUserConfigMapper.getByUserID(oaUserInfo.getUser_id());

        OADepartmentConfig oaDepartmentConfig = oaDepartmentConfigMapper.getByDepartmentID(oaUserConfig.getDepartment_id());

        List<String> userIDList = new ArrayList<>();

        if (oaDepartmentConfig.getDepartment_name().equals("总经办") ||
                oaDepartmentConfig.getDepartment_name().equals("董事办")) {
            // 总经办、董事办需要查询所有部门
            if (contractListDto.getDepartment_id() != null) {
                switch (oaUserInfo.getRole_level()) {
                    case BD:
                    case BU:
                    case CORP:
                        oaInfoService.findAllUserForDepartment(contractListDto.getDepartment_id(), userIDList);
                    default:
                }
            } else {
                switch (oaUserInfo.getRole_level()) {
                    case BD:
                    case BU:
                    case CORP:
                        oaInfoService.findAllUserForDepartment(oaDepartmentConfig.getSuperior_department_id(), userIDList);
                    default:
                }
            }
        } else {
            // 普通部门，需要根据是否为领导查询所有员工
            if (oaUserConfig.getIs_leader() == 1) {
                if (!StringUtils.isEmpty(contractListDto.getUser_token())) {
                    userIDList.add(userRelationshipMapper.getOAUserIDByToken(contractListDto.getUser_token()));
                } else {
                    List<OAUserConfig> oaUserConfigList = oaUserConfigMapper.subUserForDepartment(oaDepartmentConfig.getDepartment_id());

                    for (OAUserConfig userConfig : oaUserConfigList) {
                        userIDList.add(userConfig.getUser_id());
                    }
                }
            } else {
                userIDList.add(oaUserConfig.getUser_id());
            }
        }

        return userIDList;
    }

    /**
     * 更新合同当前运输信息（当前供应量、总金额）
     *
     * @param oaContract 合同对象
     */
    private void updateContractCurrentInfo(OAContract oaContract) {
        oaContract.setCurrent_amount(transportInfoService.sumGoodsWeight(oaContract.getMain_id()).toString());
        oaContract.setCurrent_sum(transportInfoService.sumAmount(oaContract.getMain_id()).toString());
    }

    /**
     * 根据 main_id 获取合同信息
     *
     * @param main_id
     * @return 合同信息
     */
    public OAContract getContractByMainID(String main_id) {
        OAContract oaContract = oaContractMapper.getContractByMainID(main_id);

        updateContractCurrentInfo(oaContract);

        if (oaContract.getContract_status() == 2 &&
                oaContract.getSystem_contract_status() == 2) {
            oaContract.setShow_confirm(transportInfoService.isAllAcceptanceDone(main_id));
        }

        return oaContract;
    }


    /**
     * 获取合同分页信息
     *
     * @param contractListDto 分页筛选条件
     * @param oaUserInfo      用户信息
     * @return 合同分页信息
     */
    public Page<OAContract> getContractList(ContractListDto contractListDto,
                                            OAUserInfo oaUserInfo) {
        if (oaUserInfo.getRole_level().equals(OAUserRoleLevel.OPERATOR)) {
            return null;
        }

        if (!StringUtils.isEmpty(contractListDto.getMonth())) {
            LocalDate localDate = LocalDate.parse(contractListDto.getMonth(), dateTimeFormatter);

            contractListDto.setEnd_month(localDate.plusMonths(1).toString());
        }

        List<String> userIDList = findUserIDForList(contractListDto, oaUserInfo);

        if (userIDList != null && userIDList.size() > 0) {
            contractListDto.setList(userIDList);
        }

        Page<OAContract> oaContractPage = paginationMapper.getContractList(contractListDto);

        for (OAContract oaContract : oaContractPage.getPageResult()) {
            updateContractCurrentInfo(oaContract);

            // 运输中合同 判断按钮是否显示
            if (oaContract.getContract_status() == 2 &&
                    oaContract.getSystem_contract_status() == 2) {
                oaContract.setShow_confirm(transportInfoService.isAllAcceptanceDone(oaContract.getMain_id()));
            }
        }

        return oaContractPage;
    }

    public void changStatus(ContractChangeStatusDto changeStatusDto) {
        oaContractMapper.updateSystemStatus(changeStatusDto);
    }
}
